/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.d.lib.common.widget;

import com.d.lib.common.ResourceTable;
import ohos.agp.components.*;
import ohos.app.Context;

public class TitleLayout extends DependentLayout {

  protected int mRes = -1;
  protected boolean isBack = false;
  protected boolean isMore = false;
  protected String middleTitle = "";
  protected Context mContext;
  protected Component mRootView;

  public TitleLayout(Context context, AttrSet attrSet, String styleName) {
    super(context, attrSet, styleName);
  }

  public TitleLayout(Context context, AttrSet attrSet) {
    super(context, attrSet);
    init(context, attrSet);
  }

  public TitleLayout(Context context) {
    super(context);
  }

  private void init(Context context, AttrSet attrSet) {

    isBack = attrSet.getAttr("lib_pub_tl_isBack").isPresent() ? attrSet.getAttr(
        "lib_pub_tl_isBack").get().getBoolValue() : false;
    isMore = attrSet.getAttr("lib_pub_tl_isMore").isPresent() ? attrSet.getAttr(
        "lib_pub_tl_isMore").get().getBoolValue() : false;
    middleTitle = attrSet.getAttr("lib_pub_tl_middleText").isPresent() ? attrSet.getAttr(
        "lib_pub_tl_middleText").get().getStringValue() : "";
    mRes = attrSet.getAttr("lib_pub_tl_layout").isPresent() ?
        attrSet.getAttr("lib_pub_tl_layout").get().getIntegerValue() :
        ResourceTable.Layout_lib_pub_layout_title;

    mContext = context;
    mRootView = LayoutScatter.getInstance(context).parse(mRes, this, true);

    Component backComponent = mRootView.findComponentById(ResourceTable.Id_iv_title_left);
    backComponent.setVisibility(isBack ? VISIBLE : INVISIBLE);
    Component moreComponent = mRootView.findComponentById(ResourceTable.Id_iv_title_right);
    moreComponent.setVisibility(isMore ? VISIBLE : INVISIBLE);

    Text middleComponent = (Text) mRootView.findComponentById(ResourceTable.Id_tv_title_title);
    middleComponent.setText(middleTitle);
  }

  public void setBackClickListener(final Component.ClickedListener l) {
    Component v1 = findComponentById(ResourceTable.Id_iv_title_left);
    if (v1 != null) {
      v1.setClickedListener(l);
    }
  }

  public void setMoreClickListener(final Component.ClickedListener l) {
    Component v2 = findComponentById(ResourceTable.Id_iv_title_right);
    if (v2 != null) {
      v2.setClickedListener(l);
    }
  }
}
